package com.spdzen.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spdzen.mapper.SysRoleMapper;
import com.spdzen.model.SysRole;
import com.spdzen.model.SysUserRole;
import com.spdzen.service.SysRoleResourceService;
import com.spdzen.service.SysRoleService;
import com.spdzen.service.SysUserRoleService;
import com.spdzen.support.SimpleServiceImpl;
import com.spdzen.support.exception.ResultCodeException;
import com.spdzen.support.shiro.ShiroDynamicAuthorization;

/**
 * 系统角色 服务实现类
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends SimpleServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
	@Resource
	private SysRoleResourceService sysRoleResourceService;

	@Resource
	private SysUserRoleService sysUserRoleService;

	@Override
	@Transactional(rollbackFor = { Exception.class })
	public void inserIfPermission(SysRole entity) throws Exception {
		baseMapper.insert(entity);

		SysRole record = new SysRole();
		record.setName(entity.getName());
		if (selectCount(record) > 1) {
			throw new ResultCodeException("角色名称已经存在！");
		}
	}

	@Override
	@Transactional(rollbackFor = { Exception.class })
	public void updateIfPermission(SysRole entity) throws Exception {
		baseMapper.updateById(entity);

		SysRole record = new SysRole();
		record.setName(entity.getName());
		if (selectCount(record) > 1) {
			throw new ResultCodeException("角色名称已经存在！");
		}
	}

	@Override
	@Transactional(rollbackFor = { Exception.class })
	@ShiroDynamicAuthorization
	public void deleteIfPermission(Long id) throws Exception {
		SysUserRole sur = new SysUserRole();
		sur.setSysRoleId(id);
		if (sysUserRoleService.selectCount(sur) > 0) {
			throw new ResultCodeException("角色下有用户，不能删除！");
		}

		baseMapper.deleteById(id);
		sysRoleResourceService.deleteByRole(id);
	}

}
